<?php
declare(strict_types=1);
/**
 * @project: 兔兔找图微信小程序
 * @author: kert
 * @date: 2023/5/22
 * @link: https://www.qqdeveloper.com/
 * @site: 微信搜索-兔兔找图
 */

namespace App\Library\Ai\FlagStudio;

use App\Library\HttpClient;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class FlagStudioImage extends ApiBase
{

    public function textToImage(array $imageParams = [], int $number = 1): array
    {
        if (isset($imageParams["negative_prompts"]) && $imageParams["negative_prompts"] == null) {
            unset($imageParams["negative_prompts"]);
        }
        $imageArray = [];
        if ($number > 4 || $number < 0) return [];
        for ($i = 0; $i < $number; $i++) {
            $response = HttpClient::client()->post("https://flagopen.baai.ac.cn/flagStudio/v1/text2img", [
                "json"    => $imageParams,
                "headers" => [
                    'Content-Type' => 'application/json',
                    'Accept'       => 'application/json',
                    "token"        => $this->getAccessToken(),
                ]
            ]);
            $imageInfo = json_decode($response->getBody()->getContents(), true);
            Log::info("请求信息" . json_encode($imageParams, JSON_UNESCAPED_UNICODE) . "相应信息" . json_encode($imageInfo, JSON_UNESCAPED_UNICODE));
            $imagePath = md5(uniqid()) . ".png";
            $downloadFile = Storage::disk("public_disk")->put($imagePath, base64_decode($imageInfo["data"]));
            if ($downloadFile) {
                $imageArray[] = [
                    config("app.url") . $imagePath
                ];
            }
        }
        return $imageArray;
    }
}
